//
//  RWBalancebalancePayViewController.m
//  RedWine
//
//  Created by Liufangfang on 2017/1/14.
//  Copyright © 2017年 HuiBangKe. All rights reserved.
//

#import "RWBalancePayViewController.h"

#import <AlipaySDK/AlipaySDK.h>
#import "RSADataSigner.h"
#import "Order.h"

#import "WXApi.h"

#import "RWPaySuccessViewController.h"
#import "UIViewController+BackButtonHandler.h"
#import "AppDelegate.h"
#import "RWOrderListViewController.h"
#import "RWMyOrderDetailModel.h"

#define kBalancePayButtonBaseTag 550

typedef NS_ENUM(NSInteger, RWPayStyle) {
    
    RWPayStyleApliPay = 0,
    RWPayStyleWeChat
};

@interface RWBalancePayViewController (){

    NSArray *orderLabTexts;
    NSArray *orderLabContents;
    NSArray *cellImages;
    NSArray *cellTitles;
    //订单编号
    //NSString *orderSn;
}

@property (nonatomic, strong) UIButton *aliPayBtn;
@property (nonatomic, strong) UIButton *weChatBtn;

@property (nonatomic, assign) RWPayStyle payStyle;

@end

@implementation RWBalancePayViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    //添加微信支付，支付宝支付通知
    [self addNotificaion];
    if (!self.orderSN) {
        [self loadDatas];
    }else{
        [self setNavigation];
        //[self setBalancePayUI];
        [self loadOrderDetail];
        DLog(@"orderSN:%@",self.orderSN);
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{
    
    orderLabTexts = @[@"订单编号", @"商品件数", @"订单金额"];
    cellImages = @[@"alipay_icon", @"weixin_icon"];
    cellTitles = @[@"支付宝支付", @"微信支付"];
}

//获取订单详情
- (void)loadOrderDetail
{
    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=order&member_id=%@&order_sn=%@", user.userID, _orderSN] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            DLog(@"订单详情====%@", result);
            FTYBaseShopCartModel *baseModel = [[FTYBaseShopCartModel alloc] init];
            baseModel = [FTYBaseShopCartModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                RWMyOrderDetailModel *myOrderDetailModel = [RWMyOrderDetailModel mj_objectWithKeyValues:baseModel.info];
               
                _goodNum = [NSString stringWithFormat:@"%ld",[myOrderDetailModel.goods count]];
                //_money = myOrderDetailModel.sum;
                _money = myOrderDetailModel.order_amount;
                orderLabContents = @[_orderSN, _goodNum, _money];
                [self setBalancePayUI];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
        }
    }];
}
//生成订单
- (void)loadDatas{
    
    
    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=neworder&member_id=%@&token=%@&cart_id=%@&address_id=%@&%@", user.userID, user.userToken, _cartIDs, _addressID, _jointBillParam] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            DLog(@"====%@", result);
            FTYBaseShopCartModel *baseModel = [[FTYBaseShopCartModel alloc] init];
            baseModel = [FTYBaseShopCartModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                _orderSN = baseModel.info[@"order_sn"];
                orderLabContents = @[_orderSN, _goodNum, _money];
                
                [self setNavigation];
                [self setBalancePayUI];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
        }
    }];
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = @"收银台";
}

- (BOOL)navigationShouldPopOnBackButton
{
    //跳转到购物车首页
    //[sharedDelegate showWindowHome:@"shopCart"];
    //进入待收货列表
    [self gotoPayOrder];
    return NO;
}
- (void)gotoPayOrder{
    
    RWOrderListViewController *orderListVC = [[RWOrderListViewController alloc] init];
    orderListVC.hidesBottomBarWhenPushed = YES;
    orderListVC.tableTitle = @"待付款";
    orderListVC.orderState = @"10";
    [self.navigationController pushViewController:orderListVC animated:YES];
}
- (void)setBalancePayUI{
    
    _balancePayTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT- FTY_TABBAR_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_balancePayTV];
    _balancePayTV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _balancePayTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _balancePayTV.dataSource = self;
    _balancePayTV.delegate = self;
    _balancePayTV.scrollEnabled = NO;
    _balancePayTV.tableHeaderView = [self createHeader];
    [self addBottomBtn];
}

#pragma mark - Config Invoke Methods

- (UIView *)createHeader{

    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, 100.*FTY_HEIGHT_BASE)];
    
    for (int i=0; i<3; i++) {
        
        UILabel *orderLab = [[UILabel alloc] init];
        [headerV addSubview:orderLab];
        orderLab.text = orderLabTexts[i];
        orderLab.textColor = [UIColor blackColor];
        orderLab.font = FTY_FONTTSIZE(15);
        [orderLab sizeToFit];
        [orderLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(10.*FTY_HEIGHT_BASE + (20 + 10) * i * FTY_HEIGHT_BASE);
            make.left.mas_equalTo(10.*FTY_WIDTH_BASE);
        }];
        
        UILabel *orderContentLab = [[UILabel alloc] init];
        [headerV addSubview:orderContentLab];
        orderContentLab.text = orderLabContents[i];
//        orderContentLab.text = orderLabTexts[i];
        orderContentLab.textColor = [UIColor blackColor];
        orderContentLab.font = FTY_FONTTSIZE(15);
        [orderContentLab sizeToFit];
        [orderContentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(10.*FTY_HEIGHT_BASE + (20 + 10) * i * FTY_HEIGHT_BASE);
            make.left.mas_equalTo(orderLab.mas_right).offset(10.*FTY_WIDTH_BASE);
        }];
    }
    
    return headerV;
}

- (void)addBottomBtn{
    
    UIButton *balancePayBtn = [[UIButton alloc] init];
    [self.view addSubview:balancePayBtn];
    balancePayBtn.backgroundColor = [FTYColor getMainColorWithAlpha:1.];
    balancePayBtn.layer.masksToBounds = YES;
    balancePayBtn.layer.cornerRadius = 5.*FTY_WIDTH_BASE;
    [balancePayBtn setTitle:@"提交" forState:UIControlStateNormal];
    [balancePayBtn addTarget:self action:@selector(balancePayBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [balancePayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10.*FTY_WIDTH_BASE);
        make.bottom.mas_offset(-150.*FTY_HEIGHT_BASE);
        make.right.mas_offset(-10.*FTY_HEIGHT_BASE);
        make.height.mas_offset(40.*FTY_HEIGHT_BASE);
    }];
}

#pragma mark - Notificaiton Method
- (void)addNotificaion
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatPaySuccess:) name:@"WXPay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aliPaySuccess:) name:@"ALiPay" object:nil];
}

#pragma mark - Notificaiton Invoke Methods

- (void)wechatPaySuccess:(id)sender
{
    [self paySuccess:@"微信支付"];
    
}

- (void)aliPaySuccess:(id)sender
{
    [self paySuccess:@"支付宝"];
}
- (void)paySuccess:(NSString *)msg
{
    RWPaySuccessViewController *paySuccessController = [[RWPaySuccessViewController alloc] init];
    
    [self.navigationController pushViewController:paySuccessController animated:NO];
    paySuccessController.orderId = _orderSN;
    paySuccessController.payMoney = _money;
    paySuccessController.orderType = msg;
}


#pragma mark - <UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50.*FTY_HEIGHT_BASE;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 50.*FTY_HEIGHT_BASE;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, 50.*FTY_HEIGHT_BASE)];
    headerV.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLab = [[UILabel alloc] init];
    [headerV addSubview:titleLab];
    titleLab.text = @"请选择支付方式：";
    titleLab.textColor = [FTYColor blackColor];
    titleLab.font = FTY_FONTTSIZE(15);
    [titleLab sizeToFit];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_offset(0);
        make.left.mas_offset(10*FTY_WIDTH_BASE);
        make.right.mas_offset(-10*FTY_WIDTH_BASE);
    }];
    
    return headerV;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * const balancePayID = @"balancePayID";
    UITableViewCell *balancePayCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:balancePayID];
    balancePayCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSInteger row = indexPath.row;
        
    balancePayCell.imageView.image = [UIImage imageNamed:cellImages[row]];
    balancePayCell.textLabel.text = cellTitles[row];
    balancePayCell.textLabel.font = FTY_FONTTSIZE(15);
    
    UIButton *selectBtn = [[UIButton alloc] init];
    [balancePayCell.contentView addSubview:selectBtn];
    [selectBtn setImage:[UIImage imageNamed:@"noselected_icon"] forState:UIControlStateNormal];
    [selectBtn setImage:[UIImage imageNamed:@"selected_icon"] forState:UIControlStateSelected];
    selectBtn.tag = kBalancePayButtonBaseTag + row;
    [selectBtn addTarget:self action:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(balancePayCell.mas_centerY);
        make.right.mas_equalTo(-10.*FTY_WIDTH_BASE);
        make.width.height.mas_equalTo(30.*FTY_WIDTH_BASE);
    }];
    
    if (0 == indexPath.row) {
        selectBtn.selected = YES;
        _aliPayBtn = selectBtn;
    } else {
        _weChatBtn = selectBtn;
    }
    
    if (0 == row) {
        
        UIView *line = [[UIView alloc] init];
        [balancePayCell addSubview:line];
        line.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.mas_offset(0);
            make.height.mas_offset(.5*FTY_HEIGHT_BASE);
        }];
    }
    
    return balancePayCell;
}

#pragma mark - <UITableViewDelegate>

#pragma mark - Private Invoke Methods

- (void)selectBtnAction:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    if (550 == btn.tag) {
        _payStyle = RWPayStyleApliPay;
        _weChatBtn.selected = NO;
    } else if(551 == btn.tag) {
        _payStyle = RWPayStyleWeChat;
        _aliPayBtn.selected = NO;
    }
}

- (void)balancePayBtnAction:(UIButton *)btn{
    
//    RWPaySuccessViewController *paySuccessVC = [[RWPaySuccessViewController alloc] init];
//    [self.navigationController pushViewController:paySuccessVC animated:YES];
    
    switch (_payStyle) {
            
        case RWPayStyleApliPay:
            [self gotoAplibalancePay];
            break;
            
        case RWPayStyleWeChat:
            
            if ([WXApi isWXAppInstalled]) {
                [self gotoWeChatbalancePay];
            } else { //未安装微信
                UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:nil message:@"您未安装微信客户端～" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"好的", nil];
                [alertview show];
                return;
            }
            break;
            
        default:
            break;
    }
}

#pragma mark - AplibalancePay Methods

//支付宝支付
- (void)gotoAplibalancePay{
    
    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/ali.php?member_id=%@&order_sn=%@", user.userID, _orderSN] parameters:nil block:^(id result, NSError *error) {
     
        if (!error) {
            
            NSInteger codeInfo = [[[result objectForKey:@"err"] objectForKey:@"errorcode"] integerValue];
            NSString *info = [[result objectForKey:@"err"] objectForKey:@"errorinfo"];
            NSDictionary *userInfo = result[@"info"];
            NSLog(@"RWBalancePayViewController:gotoAplibalancePay:支付宝支付 hbk后台接口返回：%@",result);
            if (0 == codeInfo) {
                [self aliPay:userInfo];
            } else {
                [[FTYToastView alloc] addTitle:info addView:self.view];
            }
        } else {
            NSLog(@"支付宝请求错误=====%@", error);
        }
    }];
}
- (void)aliPay:(NSDictionary *)dic{
    // NOTE: 调用支付结果开始支付
    
    NSString *orderString = [dic objectForKey:@"url"];
    NSString *appScheme = @"alipayHBKRedWine";
       
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
    
}

#pragma mark - WeChatBalancePay Methods

//微信支付
- (void)gotoWeChatbalancePay{
    
        [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=topay&method=%@&member_id=%@&token=%@&order_sn=%@", @"wx", [FTYUser sharedUser].userID, [FTYUser sharedUser].userToken, _orderSN] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSInteger codeInfo = [[[result objectForKey:@"err"] objectForKey:@"errorcode"] integerValue];
            NSString *info = [[result objectForKey:@"err"] objectForKey:@"errorinfo"];
            NSDictionary *userInfo = result[@"info"];
            if (0 == codeInfo) {
                [self weChat:userInfo];
            } else {
                [[FTYToastView alloc] addTitle:info addView:self.view];
            }
        } else {
            
        }
    }];
}

- (void)weChat:(NSDictionary *)dic{
    
        //NSLog(@"====%@", dic);
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    req.partnerId           = [dic objectForKey:@"partnerid"];
    req.prepayId            = [dic objectForKey:@"prepayid"];
    req.nonceStr            = [dic objectForKey:@"noncestr"];
    req.timeStamp           = [[dic objectForKey:@"timestamp"] intValue];
    req.package             = [dic objectForKey:@"packageX"];
    req.sign                = [dic objectForKey:@"sign"];
    [WXApi sendReq:req];
}

@end
